package com.wwj.study.observer.proxy;

import com.wwj.study.delegate.ProjectManager;
import com.wwj.study.observer.core.Event;
import com.wwj.study.observer.core.EventLisenter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wuweijun
 * @Date: 2018/11/22 21:50
 */
public class ProxySubject  extends EventLisenter implements InvocationHandler {

    private Map<String,SubjectEventType> map=new HashMap<>();

    private Object target;

    public ProxySubject(){
        map.put("add",SubjectEventType.add);
        map.put("delete",SubjectEventType.delete);
    }


    public Object getInstance(Object target){
        this.target=target;

        Class<?> clazz=target.getClass();
        Object obj= Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);

        Observer observer = new Observer();
        //获取观察者方法，回调方法
        Method method = null;
        try {
            method = Observer.class.getMethod("advice", Event.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        for (SubjectEventType type: map.values()) {
            this.addLisenter(type, observer, method);
        }

        return obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        method.invoke(target,args);

        String methodName= method.getName();
        trigger(map.get(methodName));
        return null;
    }
}
